package com.azxcrm.project.system.user.controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.azxcrm.common.utils.StringUtils;
import com.azxcrm.common.utils.security.ShiroUtils;
import com.azxcrm.framework.shiro.session.OnlineSessionDAO;
import com.azxcrm.framework.web.controller.BaseController;
import com.azxcrm.framework.web.domain.Message;
import com.azxcrm.project.monitor.online.domain.OnlineSession;
import com.azxcrm.project.monitor.online.domain.UserOnline;
import com.azxcrm.project.monitor.online.service.IUserOnlineService;
import com.azxcrm.project.system.user.domain.User;
import com.azxcrm.project.system.user.service.IUserService;

/**
 * 登录验证
 * 
 * @author Dustyone
 */
@Controller
public class LoginController extends BaseController
{

	@Autowired
	private IUserService iUserService;
	
	@Autowired
	private IUserOnlineService iUserOnlineService;
	
	@Autowired
    private OnlineSessionDAO onlineSessionDAO;
	
    @GetMapping("/login")
    public String login()
    {	
        return "login";
    }
    
    @GetMapping("/loginWap")
    public String loginWap()
    {
    	return "loginWap";
    }

    @PostMapping("/login")
    @ResponseBody
    public Message ajaxLogin(HttpServletRequest req, String username, String password, String tryCode,User user,UserOnline userOnline)
    {	
    	
        try
        {	
        	//WAP端暂时不做校验
        	if(StringUtils.isNotEmpty(user.getLoginSource()) && !"wap".equals(user.getLoginSource())){
        		String rightCode = (String) req.getSession().getAttribute("rightCode");
        		
        		if("".equals(rightCode) || rightCode ==null){
        			String msg = "验证码已过期，刷新重试";
                	return Message.error(msg);
        		}
        		
            	if (!rightCode.equals(tryCode)) {
            		String msg = "验证码错误";
                	return Message.error(msg);
            	}
        	}
            UsernamePasswordToken token = new UsernamePasswordToken(username, password);
            Subject subject = SecurityUtils.getSubject();
        	
        	//Shiro Realm认证
            subject.login(token);
            
            //验证用户状态：离职状态校验：1离职，0在职
            if(ShiroUtils.getUser().getIsOnboard() == 1 ){
            	String msg = "您已离职，无权登陆";
            	return Message.error(msg);
            }
            //验证用户状态：登陆状态校验：1禁止登陆，0允许登录
            if(ShiroUtils.getUser().getAccessLogin() == 1 ){
            	String msg = "登陆未授权，请联系管理员";
            	return Message.error(msg);
            }
            
            //踢出登录名相同的用户回话
            userOnline.setLoginName(username);
            List<UserOnline> userOnlineInfoList = iUserOnlineService.selectUserOnlineList(userOnline);
            
            if(userOnlineInfoList !=null && userOnlineInfoList.size()>0){
            	for(UserOnline userOnlineInfo : userOnlineInfoList){
                	OnlineSession onlineSession = (OnlineSession) onlineSessionDAO.readSession(userOnlineInfo.getSessionId());
                    if (onlineSession == null)
                    {
                        return Message.error("用户已下线");
                    }
                    onlineSession.setStatus(OnlineSession.OnlineStatus.off_line);
                    iUserOnlineService.deleteOnlineById(userOnlineInfo.getSessionId());
                }
            }
            
            user.setLoginName(username);
            //更新用户登陆来源
            iUserService.updateUserByLoginName(user);
            return Message.ok();
        }
        catch (AuthenticationException e)
        {
            String msg = "用户或密码错误";
            if (StringUtils.isNotEmpty(e.getMessage()))
            {
                msg = e.getMessage();
            }
            return Message.error(msg);
        }
    }

    @GetMapping("/unauth")
    public String unauth()
    {
        return "/error/unauth";
    }
}
